'''
RC4 加密
'''
class RC4_cipher():
    def swap_bytes(self, s, i, j):
        s[i], s[j] = s[j], s[i]

    def KSA(self, key):
        s = list(range(256))
        j = 0
        for i in range(256):
            j = (j + s[i] + key[i % len(key)])%256
            self.swap_bytes(s, i ,j)
        return s

    def PRGA(self, s):
        i = j = 0
        while True:
            i = (i + 1)%256
            j = (j + s[i])%256
            self.swap_bytes(s, i, j)
            t = (s[i] + s[j]) % 256
            yield s[t]

    def RC4_crypt(self, key, plaintext):
        s = self.KSA(key)
        prga = self.PRGA(s)
        keystream = [next(prga) for _ in plaintext]
        ciphertext = bytes([p ^ k for p, k in zip(plaintext, keystream)])
        return ciphertext